﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Threading;
using System.Globalization;
using System.Text.RegularExpressions;
using Nivdal.TBP;
using Nivdal.AuxCode;

namespace Nivdal
{
    public partial class ThreadDetails : System.Web.UI.Page
    {
        string ThreadId;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                this.NewMessageButton.Visible = false;

            if (Request.QueryString["Answer"] != null)
                this.MessageLabel.Text = Request.QueryString["Answer"].ToString();

            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            this.Title = Resources.Resource.Default_PageTitle + ", " + Resources.Resource.ThreadDetails_PageTitle;
            //this.Title = GND.ReturnAppTitle();
            //if (ou.TeamId == "Null")
            //    Response.Redirect("~/GeneralMessage.aspx?MessageString=M74ggdizz5wfeh");

            if (Request.QueryString["ThreadId"] != null)
            {
                ThreadId = Request.QueryString["ThreadId"].ToString();
                ThreadIdHiddenField.Value = ThreadId;
            }
            else
                Response.Redirect("~/ForumHomePage.aspx");
            string PostId = Request.QueryString["PostId"];
            if (PostId == null || PostId == "0")
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                    PostId = GND.ReadNivdalIntData("@UserId", "@ThreadId", "Nivdal_ForumGetCurrentPostIdInThread", ou.UserId, ThreadId);
                else
                    PostId = GND.ReadNivdalIntData("@ThreadId", "Nivdal_ForumGetCurrentPostIdInThread", ThreadId);

            if (PostId == null)
            {
                Response.Redirect("~/ForumHomePage.aspx");
            }
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (!GND.ReadNivdalBoolData("@UserId", "@ThreadId", "Nivdal_ForumCanUserSeeThread", ou.UserId, ThreadId))
                    Response.Redirect("~/ForumHomePage.aspx");
            }
            else
                if (!GND.ReadNivdalBoolData("@ThreadId", "Nivdal_ForumCanUserSeeThread", ThreadId))
                    Response.Redirect("~/ForumHomePage.aspx");

            if (!IsPostBack)
            {
                this.ThreadDetailsSqlDataSource.SelectParameters.Add("ThreadId", ThreadId);
                this.GetThreadPostsSqlDataSource.SelectParameters.Add("ThreadId", ThreadId);
                this.GetThreadPostsSqlDataSource.SelectParameters.Add("PostId", PostId);
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                    this.GetThreadPostsSqlDataSource.SelectParameters.Add("UserId", ou.UserId);
            }
            string NextPostId = GND.ReadNivdalIntData("@PostId", "Nivdal_ForumGetNextPostInThread", PostId);
            string PreviousPostId = GND.ReadNivdalIntData("@PostId", "Nivdal_ForumGetPreviousPostInThread", PostId);
            string FirstPostId = GND.ReadNivdalIntData("@PostId", "Nivdal_ForumGetFirstPostId", PostId);
            string LastPostId = GND.ReadNivdalIntData("@PostId", "Nivdal_ForumGetLastPostId", PostId);
            this.UpperNextHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + NextPostId;
            this.UpperPreviousHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + PreviousPostId;
            this.UpperFirstHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + FirstPostId;
            this.UpperLastHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + LastPostId;
            this.LowerNextHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + NextPostId;
            this.LowerPreviousHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + PreviousPostId;
            this.LowerFirstHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + FirstPostId;
            this.LowerLastHyperLink.NavigateUrl = "ThreadDetails.aspx?ThreadId=" + ThreadId + "&PostId=" + LastPostId;
            if (NextPostId == "0")
            {
                UpperNextHyperLink.Visible = false;
                LowerNextHyperLink.Visible = false;
            }
            if (PreviousPostId == "0")
            {
                UpperPreviousHyperLink.Visible = false;
                LowerPreviousHyperLink.Visible = false;
            }
            if (FirstPostId == "0")
            {
                UpperFirstHyperLink.Visible = false;
                LowerFirstHyperLink.Visible = false;
            }
            if (LastPostId == "0")
            {
                UpperLastHyperLink.Visible = false;
                LowerLastHyperLink.Visible = false;
            }

            this.AdminCloseThreadButton.Visible = GND.ReadNivdalBoolData("@UserId", "@ThreadId", "Nivdal_CanUserCloseThread", ou.UserId, ThreadId);
            string ThreadName = GND.ReadNivdalStringData("@ThreadId", "Nivdal_ForumGetThreadNameByThreadId", ThreadId);
            this.Title = ThreadName + " - Nivdal.com";
            this.PageNameLabel.Text = ">> " + ThreadName;
            this.PageNameForumHyperLink.Text = GND.ReadNivdalStringData("@ThreadId", "Nivdal_ForumGetForumNameByThreadId", ThreadId);
            string ForumId = GND.ReadNivdalStringData("@ThreadId", "Nivdal_ForumGetForumIdByThreadId", ThreadId);
            this.ForumIdHiddenField.Value = ForumId;
            this.PageNameForumHyperLink.NavigateUrl = "ForumDetails.aspx?Id=" + ForumId;

            //this.MessageLabel.Text = GND.ReadNivdalBoolData("@UserId", "@ThreadId", "Nivdal_ForumCanUserSeeThread", UsrId, ThreadId).ToString();



        }

        protected void DeleteTheThread(string PostId)
        {
            string ThreadId = null;
            if (Request.QueryString["ThreadId"] != null)
                ThreadId = Request.QueryString["ThreadId"].ToString();

            else
                Response.Redirect("~/ForumHomePage.aspx");
            //Response.Write(PostId);
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UsrId = GND.ReturnUserId();

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_ForumDeletePost";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_PostId = new SqlParameter();
            dbParam_PostId.ParameterName = "@PostId";
            dbParam_PostId.Value = PostId;
            dbParam_PostId.DbType = DbType.Decimal;
            dbCommand.Parameters.Add(dbParam_PostId);

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = UsrId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                this.MessageLabel.Text = dbParam_Answer.Value.ToString();
                this.GetThreadPostsListView.DataBind();
                //Response.AddHeader("Refresh", "1");
                ///Response.Redirect("ThreadDetails.aspx?ThreadId=" + ThreadId +"Answer=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.MessageLabel.Text = Convert.ToString(SQLDBException);
                return;

            }

            finally
            {
                dbConnection.Close();
            }

        }
        protected string ReplaceEOL(string input)
        {
            //return input.Replace("\r\n", "<br /> ").Replace("\n", "<br /> ");
            return (GlobalFunctions.LightEncodeHtmlFromText(input));
        }

        protected void GetThreadPostsListView_OnItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (String.Equals(e.CommandName, "DeleteThread"))
            {
                ListViewDataItem dataItem = (ListViewDataItem)e.Item;
                string PostId =
                  GetThreadPostsListView.DataKeys[dataItem.DisplayIndex].Value.ToString();
                DeleteTheThread(PostId);

            }

            if (String.Equals(e.CommandName, "EditThread"))
            {
                string ThreadId = null;
                if (Request.QueryString["ThreadId"] != null)
                {
                    ThreadId = Request.QueryString["ThreadId"].ToString();
                    this.ThreadDetailsSqlDataSource.SelectParameters.Add("ThreadId", ThreadId);
                }
                else
                    Response.Redirect("~/ForumHomePage.aspx");
                ListViewDataItem dataItem = (ListViewDataItem)e.Item;
                string PostId =
                  GetThreadPostsListView.DataKeys[dataItem.DisplayIndex].Value.ToString();
                ///Response.Redirect("WriteForumPost.aspx?ThreadId=" + ThreadId + "&ReplyToPost=" + PostId + "&ReplyToUser=" + PostedById);
                Response.Redirect("EditForumPost.aspx?PostId=" + PostId);

            }

            if(string.Equals(e.CommandName, "Report"))
            {
                Response.Redirect("ReportForumBehaviour.aspx?PostId=" + e.CommandArgument); 
            }


        }




        protected void DeleteThread(Object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "DeleteThread")
            {
                // get the row index stored in the CommandArgument property
                int index = Convert.ToInt32(e.CommandArgument);
                DeleteTheThread(index.ToString());
            }
            else
                Response.Redirect("GeneralMessage.aspx?MessageString=QAZ3AlalaAXHLOB");
        }

        protected void AdminCloseThreadButton_Click(object sender, EventArgs e)
        {

            string ThreadId = null;
            if (Request.QueryString["ThreadId"] != null)
                ThreadId = Request.QueryString["ThreadId"].ToString();
            else
                Response.Redirect("~/ForumHomePage.aspx");
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            string UsrId = GND.ReturnUserId();

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_ForumCloseThread";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;

            SqlParameter dbParam_ThreadId = new SqlParameter();
            dbParam_ThreadId.ParameterName = "@ThreadId";
            dbParam_ThreadId.Value = ThreadId;
            dbParam_ThreadId.DbType = DbType.Decimal;
            dbCommand.Parameters.Add(dbParam_ThreadId);

            SqlParameter dbParam_UserId = new SqlParameter();
            dbParam_UserId.ParameterName = "@UserId";
            dbParam_UserId.Value = UsrId;
            dbParam_UserId.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_UserId);

            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                Response.Redirect("ThreadDetails.aspx?ThreadId=" + ThreadId + "Answer=" + dbParam_Answer.Value.ToString());
            }
            catch (Exception SQLDBException)
            {
                this.MessageLabel.Text = Convert.ToString(SQLDBException);
                return;

            }

            finally
            {
                dbConnection.Close();
            }

        }

        protected void NewMessageButtonClick(object sender, EventArgs e)
        {
            Response.Redirect("WriteForumPost.aspx?ThreadId=" + ThreadId);
        }

        protected string NumPostImage(Object Num)
        {
            string FileName = "";
            decimal NumPosts = (decimal)Num;

            if (NumPosts >= 5000) FileName = "~/Images/Icons/forum05.jpg";
            else if (NumPosts >= 1000) FileName = "~/Images/Icons/forum04.jpg";
            else if (NumPosts >= 200) FileName = "~/Images/Icons/forum03.jpg";
            else if (NumPosts >= 50) FileName = "~/Images/Icons/forum02.jpg";
            else FileName = "~/Images/Icons/forum01.jpg";

            return (FileName);
        }

        protected override void InitializeCulture()
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ou.UICulture);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ou.Culture);
        }

        protected string ReportImageButtonOnClientClick()
        {
            return ("return confirm('" + Resources.Resource.ThreadDetails_ReportImageButtonOnClientClick + "')");
        }

        protected string DeleteImageButtonOnClientClick()
        {
            return ("return confirm('" + Resources.Resource.ThreadDetails_DeleteImageButtonOnClientClick + "')");
        }

        protected ContentDirection CorrectDirection()
        {
            return ((Master.Master.FindControl("DirectionPanel") as Panel).Direction);
        }


        //protected string ReturnCorrectedForumString(object post)
        //{
        //    //return Regex.Replace(post.ToString(), "a{0}a", "b{0}b");
        //    MatchEvaluator Evaluator = new MatchEvaluator(ReplaceBold);
        //    return (Regex.Replace(post.ToString(), "[player=?<num>]", ""));
        //}

        //protected string ReplaceBold(Match m)
        //{
        //    return (m.Value.Replace("[player]", "<a href=\"http://www.nivdal.com/Player.aspx?Id=").Replace("[/player]", ">{0}</a>"));


        //    //return m.Value.Replace("[/b]", "</b>");
        //}
        protected bool IsModerator()
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            bool IsAdmin = GND.ReadNivdalBoolData("UserId", "ForumId", "Nivdal_ForumCanUserAdministerForum", GND.ReturnUserId(), ForumIdHiddenField.Value);
            return (IsAdmin);
        }

        protected string ReturnConvertedForumString(Object Input)
        {
            //string InputString = Input.ToString();

            //TBP.ForumConvert FC = new ForumConvert();
            //return FC.ForumConvertString(InputString);
            return (ReplaceEOL(Input.ToString()));

        }

        protected string ThreadBody(Object TB)
        {
            string TBSrc = TB.ToString();
            return GlobalFunctions.EncodeHtmlFromText(TBSrc);
        }

        protected Boolean IsUserAuthenticated()
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
                return false;
            else
                return true;
        }
    }
}